package com.ruoyi.yanjing.config;

import com.ruoyi.yanjing.client.MqttPushClient;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * MQTT 配置类
 */
@Component
@ConfigurationProperties("spring.mqtt")
public class MqttConfig {
    private static final Logger logger = LoggerFactory.getLogger(MqttConfig.class);

    @Autowired
    private MqttPushClient mqttPushClient;

    private String username;
    private String password;
    private String hostUrl;
    private String clientId;
    private String defaultTopic;
    private int timeout;
    private int keepalive;
    private boolean enabled;
    private int reconnectInterval;


//    private static final ScheduledExecutorService reconnectScheduler = Executors.newSingleThreadScheduledExecutor();
    private static boolean isReconnecting = false;

    // 记录已订阅的主题
    private static final ConcurrentSkipListSet<String> subscribedTopics = new ConcurrentSkipListSet<>();

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public int getReconnectInterval() {
        return reconnectInterval;
    }

    public void setReconnectInterval(int reconnectInterval) {
        this.reconnectInterval = reconnectInterval;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getHostUrl() {
        return hostUrl;
    }

    public void setHostUrl(String hostUrl) {
        this.hostUrl = hostUrl;
    }

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public String getDefaultTopic() {
        return defaultTopic;
    }

    public void setDefaultTopic(String defaultTopic) {
        this.defaultTopic = defaultTopic;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public int getKeepalive() {
        return keepalive;
    }

    public void setKeepalive(int keepalive) {
        this.keepalive = keepalive;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    @Bean
    public MqttPushClient getMqttPushClient() {
        if (enabled) {
            // 初始化时订阅默认主题
            String[] mqttTopics = StringUtils.split(defaultTopic, ",");
            mqttPushClient.connect(hostUrl, clientId, username, password, timeout, keepalive);
            if (mqttTopics != null) {
                for (String topic : mqttTopics) {
                    if (subscribedTopics.add(topic)) { // 避免重复订阅
                        mqttPushClient.subscribe(topic, 0);
                    }
                }
            }
        }

        return mqttPushClient;
    }

    // 动态添加主题订阅
    public void addTopicSubscription(String topic) {
        if (enabled && subscribedTopics.add(topic)) { // 避免重复订阅
            mqttPushClient.subscribe(topic, 0);
            System.out.println("Subscribed to new topic: " + topic);
        } else {
            System.out.println("Topic already subscribed or MQTT not enabled: " + topic);
        }
    }

    public MqttPushClient addTopicSubscriptionForLoseConnected() {
        if (enabled) {
            if (!isReconnecting) {
                isReconnecting = true;
                ScheduledExecutorService reconnectScheduler = Executors.newSingleThreadScheduledExecutor(); // 每次创建一个新的实例
                reconnectScheduler.scheduleAtFixedRate(() -> {
                    try {
                        logger.info("尝试重新连接MQTT...");
                        mqttPushClient.connectToBroker(); // 调用封装的重连逻辑
                        logger.info("MQTT重连成功");
                        isReconnecting = false;
                        reconnectScheduler.shutdown(); // 关闭当前的任务
                    } catch (Exception e) {
                        logger.error("MQTT重连失败: {}", e.getMessage());
                    }
                }, 0, reconnectInterval, TimeUnit.SECONDS);
            }
        }
        return mqttPushClient;
    }

//    //重连时使用
//    public MqttPushClient addTopicSubscriptionForLoseConnected() {
//        if (enabled) {
//            if (!isReconnecting) {
//                isReconnecting = true;
//                reconnectScheduler.scheduleAtFixedRate(() -> {
//                    try {
//                        logger.info("尝试重新连接MQTT...");
//                        mqttPushClient.connectToBroker(); // 调用封装的重连逻辑
//                        logger.info("MQTT重连成功");
//                        isReconnecting = false;
//                        reconnectScheduler.shutdown();
//                    } catch (Exception e) {
//                        logger.error("MQTT重连失败: {}", e.getMessage());
//                    }
//                }, 0, reconnectInterval, TimeUnit.SECONDS);
//            }
//        }
//        return mqttPushClient;
//    }
}
